package com.yunwaikeji.gy_tool_library.utils;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;

import java.util.Map;

public class GYJsonUtils {
    /**
     * 拼接字符串
     *
     * @param jsonObject
     * @return
     */
    public static String toQueryString(JsonObject jsonObject, String first) {
        if (jsonObject == null) {
            return "";
        }
        StringBuilder string = new StringBuilder(first);
        Gson gson = new Gson();
        Map<String, Object> map = gson.fromJson(jsonObject, new TypeToken<Map<String, Object>>() {
        }.getType());
        for (String keyString : map.keySet()) {
            string.append(keyString).append("=").append(jsonObject.get(keyString)).append("&");
        }
        if (string.length() > 0) {
            string = new StringBuilder(string.substring(0, string.length() - 1));
        }
        return string.toString().replace("\"", "");
    }

    public static String toQueryString(JsonObject jsonObject) {
        return toQueryString(jsonObject, "?");
    }

    /**
     * 拼接字符串
     *
     * @param objectMap
     * @return
     */
    public static String toQueryString(Map<Object, Object> objectMap, String first) {
        if (objectMap == null) {
            return "";
        }
        StringBuilder string = new StringBuilder(first);
        for (Object keyString : objectMap.keySet()) {
            string.append(keyString).append("=").append(objectMap.get(keyString)).append("&");
        }
        if (string.length() > 0) {
            string = new StringBuilder(string.substring(0, string.length() - 1));
        }
        return string.toString().replace("\"", "");
    }

    public static String toQueryString(Map<Object, Object> objectMap) {
        return toQueryString(objectMap, "?");
    }

    /**
     * json转String
     *
     * @param object
     * @return
     */
    public static String toJsonString(Object object) {
        if (object == null) {
            return "";
        }
        Gson gson = new Gson();
        return gson.toJson(object);
    }
}
